import 'dart:async';

import 'package:flutter/material.dart';

class AnimatedNum extends StatefulWidget {
  @override
  _AnimatedNumState createState() => _AnimatedNumState();
}

class _AnimatedNumState extends State<AnimatedNum> {
  double _num = 0.0;
  Timer? _timer;

  void startTime() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      setState(() {
        if (_num < 12) {
          _num++;
        } else {
          _num = 0;
        }
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('计数器组件'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
                color: Colors.black,
                padding: EdgeInsets.symmetric(horizontal: 20),
                width: 300,
                height: 120,
                child: TweenAnimationBuilder(
                  tween: Tween<double>(begin: 0.0, end: _num),
                  duration: Duration(milliseconds: 500),
                  builder: (ctx, value, child) {
                    int _text = value.floor();
                    double decimal = value - _text;

                    print('$decimal');
                    return Stack(
                      children: [
                        Positioned(
                            top: -100 * decimal,
                            child: Opacity(
                              opacity: 1 - decimal, // 1 => 0
                              child: Text(
                                '$_text',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 100),
                              ),
                            )),
                        Positioned(
                            top: 100 - 100 * decimal,
                            child: Opacity(
                              opacity: decimal, // 1 => 0
                              child: Text(
                                '${_text + 1}',
                                style: TextStyle(
                                    color: Colors.white, fontSize: 100),
                              ),
                            ))
                      ],
                    );
                  },
                )),
            ElevatedButton(
                onPressed: () {
                  startTime();
                },
                child: Text('启动'))
          ],
        ),
      ),
    );
  }
}
